package com.cwh.taskcenter.reward.executor.command;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.exception.BizException;
import com.cwh.taskcenter.domain.common.LockConstants;
import com.cwh.taskcenter.reward.strategy.RewardStrategy;
import com.cwh.taskcenter.reward.strategy.RewardStrategyFactory;
import com.cwh.taskcenter.lock.DistributedLock;
import com.cwh.taskcenter.reward.dto.GrantRewardCmd;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author cwh
 */
@Slf4j
@Component
public class GrantRewardCmdExe {

    @Autowired
    private DistributedLock distributedLock;

    @Autowired
    private RewardStrategyFactory rewardStrategyFactory;

    public Response execute(GrantRewardCmd cmd) {
        String lockKey = LockConstants.LOCK_KEY_GRANT_REWARD + cmd.getTaskId() + ":" + cmd.getUserId();
        try {
            boolean lock = distributedLock.tryLock(lockKey, 30, 30, TimeUnit.SECONDS);
            if (!lock) {
                return Response.buildFailure("LOCK_FAILED", "获取锁失败");
            }
            RewardStrategy strategy = rewardStrategyFactory.getStrategy(cmd.getRewardType());
            strategy.grantReward(cmd);
        } catch (Exception e) {
            log.error("奖励发放失败",e);
            throw new BizException("REWARD_GRANT_FAILED", "奖励发放失败");
        }
        return Response.buildSuccess();
    }

}
